<template>
    <div class="main">
        <div class="top">
            <button @click="back()" class="button">
                <div class="button-box">
                    <span class="button-elem">
                        <svg viewBox="0 0 46 40" xmlns="http://www.w3.org/2000/svg">
                            <path
                                d="M46 20.038c0-.7-.3-1.5-.8-2.1l-16-17c-1.1-1-3.2-1.4-4.4-.3-1.2 1.1-1.2 3.3 0 4.4l11.3 11.9H3c-1.7 0-3 1.3-3 3s1.3 3 3 3h33.1l-11.3 11.9c-1 1-1.2 3.3 0 4.4 1.2 1.1 3.3.8 4.4-.3l16-17c.5-.5.8-1.1.8-1.9z">
                            </path>
                        </svg>
                    </span>
                    <span class="button-elem">
                        <svg viewBox="0 0 46 40">
                            <path
                                d="M46 20.038c0-.7-.3-1.5-.8-2.1l-16-17c-1.1-1-3.2-1.4-4.4-.3-1.2 1.1-1.2 3.3 0 4.4l11.3 11.9H3c-1.7 0-3 1.3-3 3s1.3 3 3 3h33.1l-11.3 11.9c-1 1-1.2 3.3 0 4.4 1.2 1.1 3.3.8 4.4-.3l16-17c.5-.5.8-1.1.8-1.9z">
                            </path>
                        </svg>
                    </span>
                </div>
            </button>
            <span style="font-size: 25px;">
                开始协作
            </span>
        </div>
        <div class="main-body">
            <el-form :model="article" label-width="auto" style="max-width: 900px">
                <el-form-item label="文章标题">
                    <el-input @change="onTitleChange" v-model="article.title" />
                </el-form-item>
                <el-form-item v-show="collaboratorId != userId" label="协作人">
                    <el-button type="primary" @click="articleStore.isCollaboratorOpen = true">邀请协作人</el-button>
                </el-form-item>
                <el-form-item label="正在协作">
                    <div v-if="collaborators.length > 0"
                        style="margin-top: 10px; display: flex; flex-wrap: wrap; gap: 10px;">
                        <div v-for="collaborator in collaborators" :key="collaborator.id" class="collaborator-card">
                            <img v-if="collaborator.avatar" :src="`${config.downloadUrl}?name=${collaborator.avatar}`"
                                alt="avatar" class="collaborator-avatar" />
                            <span class="collaborator-name">{{ collaborator.username || "未知用户" }}</span>
                        </div>
                    </div>
                    <div v-else>
                        暂无
                    </div>
                </el-form-item>
                <el-form-item label="文章封面">
                    <el-upload class="avatar-uploader" :action="actionUrl" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeUpload">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item v-show="collaboratorId != userId" label="文章状态">
                    <el-select v-model="article.status" placeholder="请选择要保存文章的状态">
                        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="文章内容">
                    <v-md-editor v-model="article.content" height="500px" @change="onContentChange" />
                </el-form-item>
                <el-form-item>
                    <el-button style="margin-left: 800px;" type="primary" @click="onSubmit()">保存或提交审核</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
    <collaborator v-if="articleStore.isCollaboratorOpen" />
    <draw v-if="callingStore.isOpen" />
</template>

<script setup>
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import router from '../../router'
import { getDetails, updateArticle, addCollaboratorId } from '../../api/article'
import { useArticleStore } from '../../stores/article'
import { onMounted, reactive, ref, onBeforeUnmount, watch } from 'vue'
import { getuserMessage } from '../../api/user'
import collaborator from './component/collaborator.vue'
import config from '../../../public/config'
import draw from './component/draw.vue'
import { useCallingStore } from '../../stores/calling'
import { debounce } from "lodash";

let actionUrl = config.uploadUrl
const callingStore = useCallingStore()
const imageUrl = ref('')
const articleStore = useArticleStore()
const collaborators = ref([]) // 存储协作人信息
let socket = null // WebSocket 实例
let heartbeatInterval = null // 心跳定时器
let reconnectAttempts = 0 // 重连次数
const maxReconnectAttempts = 5 // 最大重连次数
const reconnectDelay = 3000 // 重连延迟时间（3秒）
const collaboratorId = ref('')
const userId = localStorage.getItem("userId")
const fetchedCollaborators = new Set(); // 记录已获取的协作人 ID



const article = reactive({
    title: '',
    content: '',
    status: '',
    pic: '',
    id: articleStore.articleId
})

const statusOptions = ref([
    { label: '私有', value: 2 },
    { label: '草稿', value: 0 },
    { label: '发布(提交审核)', value: 3 },
    { label: '邀请协作', value: 5 }
])

onMounted(() => {
    getArticleDetails()
    connectWebSocket() // 连接 WebSocket
    fetchCollaboratorsData()
})

onBeforeUnmount(() => {
    if (socket) {
        socket.close()
    }
    stopHeartbeat() // 停止心跳
})
const fetchCollaboratorsData = async () => {
    if (!collaborators.value.length) return; // 避免无效请求
    try {
        const results = await Promise.all(collaborators.value.map(async (collaborator) => {
            const params = new URLSearchParams();
            params.append("id", collaborator.id);
            const { data } = await getuserMessage(params);
            return {
                ...collaborator,
                username: data.username,
                avatar: data.avatar,
            };
        }));
        collaborators.value = results;
    } catch (error) {
        console.error("获取协作人信息失败:", error);
    }
};

// 监听 collaborators 变化，避免过多 API 请求
watch(
    () => collaborators.value.map(c => c.id).join(","), // 监听协作人 ID 变化
    async () => {
        // 过滤掉已经获取过的 ID，避免重复请求
        const newCollaborators = collaborators.value.filter(c => !fetchedCollaborators.has(c.id));

        if (newCollaborators.length === 0) return; // 没有新协作人就不请求

        await fetchCollaboratorsData();

        // 记录已经获取的 ID
        newCollaborators.forEach(c => fetchedCollaborators.add(c.id));
    },
    { deep: false, immediate: true }
);
// 获取文章详情
async function getArticleDetails() {
    const params = new URLSearchParams
    params.append("id", articleStore.articleId)
    await getDetails(params).then(res => {
        if (res.code == 200) {
            article.title = res.data.title
            getArticleUser(res.data.userId)
            article.content = res.data.content
            imageUrl.value = `${config.downloadUrl}?name=${res.data.pic}`
            article.status = res.data.status
            article.pic = res.data.pic
            collaboratorId.value = res.data.collaboratorId
        }
    })
}

// 获取文章作者信息
async function getArticleUser(id) {
    const params = new URLSearchParams
    params.append("id", id)
    await getuserMessage(params).then(res => {
        if (res.code == 200) {
            article.user = res.data.username
        }
    })
}

// 连接 WebSocket
function connectWebSocket() {
    const articleId = articleStore.articleId
    const userId = localStorage.getItem("userId")
    if (!articleId || !userId) {
        console.error("Missing documentId or userId")
        return
    }

    socket = new WebSocket(config.WS_Article)

    socket.onopen = () => {
        console.log('WebSocket connected')
        reconnectAttempts = 0 // 重置重连次数
        startHeartbeat() // 启动心跳
    }

    socket.onmessage = (event) => {
        const message = JSON.parse(event.data)
        if (message.type === 'content_update') {
            article.content = message.content
            article.pic = message.pic
            imageUrl.value = `${config.downloadUrl}?name=${message.pic}`
            // 检查 userId 是否已经存在于 collaborators 中
            if (message.userid && !collaborators.value.some(collaborator => collaborator.id === message.userid)) {
                // 如果 userId 不存在，则将其添加到 collaborators 中
                collaborators.value.push({ id: message.userid });
            }
        }
        if(message.type === 'title_update'){
            article.title = message.title
        }
    }

    socket.onclose = () => {
        console.log('WebSocket disconnected')
        stopHeartbeat() // 停止心跳
        if (reconnectAttempts < maxReconnectAttempts) {
            reconnectAttempts++
            console.log(`Reconnecting in ${reconnectDelay / 1000} seconds...`)
            setTimeout(() => {
                connectWebSocket() // 重连
            }, reconnectDelay)
        } else {
            console.error('Max reconnection attempts reached')
        }
    }

    socket.onerror = (error) => {
        console.error('WebSocket error:', error)
        socket.close() // 关闭连接，触发 onclose 事件
    }
}

// 启动心跳
function startHeartbeat() {
    heartbeatInterval = setInterval(() => {
        if (socket && socket.readyState === WebSocket.OPEN) {
            socket.send(JSON.stringify({ type: 'ping' }))
        }
    }, 30000) // 每 30 秒发送一次心跳
}

// 停止心跳
function stopHeartbeat() {
    if (heartbeatInterval) {
        clearInterval(heartbeatInterval)
    }
}

const debouncedContentChange = debounce((content) => {
    if (socket && socket.readyState === WebSocket.OPEN) {
        socket.send(JSON.stringify({
            type: 'content_update',
            content: content,
            articleId: articleStore.articleId,
            userid: localStorage.getItem("userId"),
            pic: article.pic,
        }));
    }
}, 500); // 500ms 内只发送一次
function onContentChange(content) {
    debouncedContentChange(content);
}
// // 内容变化时发送更新
// function onContentChange(content) {
//     if (socket && socket.readyState === WebSocket.OPEN) {
//         const message = JSON.stringify({
//             type: 'content_update',
//             content: content,
//             articleId: articleStore.articleId,
//             userid: localStorage.getItem("userId"),
//             pic: article.pic,
//         })
//         socket.send(message)
//     } else {
//         console.warn('WebSocket is not open, message not sent.')
//     }
// }

function onTitleChange(title) {
    if (socket && socket.readyState === WebSocket.OPEN) {
        const message = JSON.stringify({
            type:'title_update',
            title:title
        })
        socket.send(message)
    } else {
        console.warn('WebSocket is not open, message not sent.')
    }
}

// 返回上一页
function back() {
    ElMessageBox.confirm(
        '确定要退出吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            router.back()
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消返回',
            })
        })
}
async function onSubmit() {
    await updateArticle(article)
        .then(res => {
            if (res.code === 200) {
                ElNotification({
                    title: '成功',
                    message: res.data,
                    type: 'success',
                    showClose: false,
                });
                router.back()
            }
            else {
                ElNotification({
                    title: '失败',
                    message: res.data,
                    type: 'error',
                    showClose: false,
                });
            }
        })
}

//图片上传成功后的方法
function handleAvatarSuccess(response, file, fileList) {
    imageUrl.value = `${config.downloadUrl}?name=${response.data}`
    article.pic = response.data
}
//上传图片之前
function beforeUpload(file) {
    if (file) {
        const suffix = file.name.split('.')[1]
        const size = file.size / 1024 / 1024 < 2
        if (['png', 'jpeg', 'jpg'].indexOf(suffix) < 0) {
            ElMessage({
                type: 'info',
                message: '上传图片只支持 png、jpeg、jpg 格式！',
            })
            // this.$message.error('上传图片只支持 png、jpeg、jpg 格式！')
            // this.$refs.upload.clearFiles()
            return false
        }
        if (!size) {
            ElMessage({
                type: 'info',
                message: '上传文件大小不能超过 2MB!',
            })
            // this.$message.error('上传文件大小不能超过 2MB!')
            return false
        }
        return file
    }
}
</script>

<style scoped>
.main {
    width: 100%;
    display: flex;
    flex-direction: column;
    overflow-y: auto;
}

.main-body {
    margin-top: 20px;
    display: flex;
    flex-direction: column;
}

::-webkit-scrollbar {
    width: 10px;
}

::-webkit-scrollbar-track {
    background: #dfe4ed;
    border-radius: 10px;
}

::-webkit-scrollbar-thumb {
    background: linear-gradient(180deg, #4b79a1, #283e51);
    border-radius: 10px;
}

::-webkit-scrollbar-thumb:hover {
    background: linear-gradient(180deg, #3b607e, #1b2e38);
}

.top {
    display: flex;
    flex-direction: row;
    align-items: center
}

.button {
    display: block;
    position: relative;
    width: 56px;
    height: 56px;
    margin: 0;
    overflow: hidden;
    outline: none;
    background-color: transparent;
    cursor: pointer;
    border: 0;
}

.button:before,
.button:after {
    content: "";
    position: absolute;
    border-radius: 50%;
    inset: 7px;
}

.button:before {
    border: 4px solid #0d2ad2;
    transition: opacity 0.4s cubic-bezier(0.77, 0, 0.175, 1) 80ms,
        transform 0.5s cubic-bezier(0.455, 0.03, 0.515, 0.955) 80ms;
}

.button:after {
    border: 4px solid #040013;
    transform: scale(1.3);
    transition: opacity 0.4s cubic-bezier(0.165, 0.84, 0.44, 1),
        transform 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94);
    opacity: 0;
}

.button:hover:before,
.button:focus:before {
    opacity: 0;
    transform: scale(0.7);
    transition: opacity 0.4s cubic-bezier(0.165, 0.84, 0.44, 1),
        transform 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94);
}

.button:hover:after,
.button:focus:after {
    opacity: 1;
    transform: scale(1);
    transition: opacity 0.4s cubic-bezier(0.77, 0, 0.175, 1) 80ms,
        transform 0.5s cubic-bezier(0.455, 0.03, 0.515, 0.955) 80ms;
}

.button-box {
    display: flex;
    position: absolute;
    top: 0;
    left: 0;
}

.button-elem {
    display: block;
    width: 20px;
    height: 20px;
    margin: 17px 18px 0 18px;
    transform: rotate(180deg);
    fill: #190a65;
}

.button:hover .button-box,
.button:focus .button-box {
    transition: 0.4s;
    transform: translateX(-56px);
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

.collaborator-card {
    display: flex;
    align-items: center;
    padding: 6px 12px;
    background-color: #f5f5f5;
    border-radius: 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    font-size: 14px;
    color: #333;
    transition: all 0.3s ease;
}

.collaborator-card:hover {
    background-color: #e0e0e0;
}

.collaborator-avatar {
    width: 24px;
    height: 24px;
    border-radius: 50%;
    margin-right: 8px;
}

.collaborator-name {
    font-weight: 500;
    cursor: pointer;
}
</style>
